#!/usr/bin/env node
/**
 * Phase2 字段映射生成器
 * 用法：node scripts/phase2/generate-field-mapping.js ComponentName
 *
 * 追溯 requirement-fields → preview-props-schema 字段转换过程
 * 实施分析报告建议2: 追溯链完善
 */

const fs = require('fs');
const path = require('path');

/**
 * 加载 component-style-standard-pattern.md 规范
 */
function loadNamingStandards() {
  const standardPath = path.join(__dirname, '../../Workflow/FigmaMCPWorkflow/Resources/templates/component-style-standard-pattern.md');

  if (!fs.existsSync(standardPath)) {
    console.warn(`⚠️  component-style-standard-pattern.md 未找到`);
    return {};
  }

  // 常见规范化映射
  return {
    'backgroundColor': 'bgColor',
    'backgroundImage': 'bgImg',
    'backgroundColorOpacity': 'bgColorOpacity',
    'hasBackground': 'hasBg',
    'showTitleBar': 'showTitleBar',
    'showMore': 'showMore'
  };
}

/**
 * 加载 DATA_TYPE_CORRECTION_GUIDE 类型转换规则
 */
function loadTypeTransformRules() {
  return {
    iconFields: {
      pattern: /Icon$/,
      from: 'string',
      to: 'IconItem[]',
      guide: 'DATA_TYPE_CORRECTION_GUIDE.md 第4节'
    },
    imageFields: {
      pattern: /(Img|Image)$/,
      from: 'string',
      to: 'string',
      guide: 'DATA_TYPE_CORRECTION_GUIDE.md 第5节'
    },
    booleanFields: {
      pattern: /^(has|show)/,
      from: 'boolean',
      to: "'Y'|'N'",
      guide: 'DATA_TYPE_CORRECTION_GUIDE.md 第1节'
    }
  };
}

/**
 * 匹配字段类型转换
 */
function matchTypeTransform(fieldName, requirementType, previewType, rules) {
  for (const [category, rule] of Object.entries(rules)) {
    if (rule.pattern.test(fieldName)) {
      if (requirementType !== previewType) {
        return {
          from: requirementType,
          to: previewType,
          reason: `类型转换（${rule.guide}）`,
          category
        };
      }
    }
  }
  return null;
}

/**
 * 生成字段映射
 */
function generateFieldMapping(componentName) {
  const root = process.cwd();

  // 读取 requirement-fields.json
  const requirementPath = path.join(root, componentName, 'phase0/requirement-fields.json');
  if (!fs.existsSync(requirementPath)) {
    throw new Error(`requirement-fields.json 不存在: ${requirementPath}`);
  }
  const requirement = JSON.parse(fs.readFileSync(requirementPath, 'utf8'));

  // 读取 preview-props-schema.json
  const schemaPath = path.join(root, componentName, 'phase2/preview-props-schema.json');
  if (!fs.existsSync(schemaPath)) {
    throw new Error(`preview-props-schema.json 不存在: ${schemaPath}`);
  }
  const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));

  console.log(`\n📋 Phase2 字段映射生成`);
  console.log(`  组件: ${componentName}`);

  const namingStandards = loadNamingStandards();
  const typeRules = loadTypeTransformRules();

  // 提取字段
  const requirementFields = {};
  ['meta', 'content', 'style', 'public'].forEach(layer => {
    if (requirement[layer]) {
      Object.entries(requirement[layer]).forEach(([field, def]) => {
        requirementFields[field] = {
          type: def.type || 'string',
          layer,
          source: def.source || 'unknown'
        };
      });
    }
  });

  const previewFields = {};
  if (schema.props) {
    Object.entries(schema.props).forEach(([field, def]) => {
      previewFields[field] = {
        type: def.type || 'string',
        defaultValue: def.default
      };
    });
  }

  console.log(`  requirement字段: ${Object.keys(requirementFields).length}`);
  console.log(`  preview字段: ${Object.keys(previewFields).length}`);

  // 生成映射表
  const mappings = [];
  const removed = [];
  const added = [];

  // 1. 处理直接映射
  Object.keys(requirementFields).forEach(reqField => {
    if (previewFields[reqField]) {
      // 字段名一致
      const typeTransform = matchTypeTransform(
        reqField,
        requirementFields[reqField].type,
        previewFields[reqField].type,
        typeRules
      );

      mappings.push({
        requirementField: reqField,
        previewProp: reqField,
        reason: typeTransform ? typeTransform.reason : '字段直接映射',
        typeTransform: typeTransform ? `${typeTransform.from} → ${typeTransform.to}` : null,
        layer: requirementFields[reqField].layer
      });
    } else {
      // 检查规范化映射
      const standardName = namingStandards[reqField];
      if (standardName && previewFields[standardName]) {
        mappings.push({
          requirementField: reqField,
          previewProp: standardName,
          reason: '规范化命名（component-style-standard-pattern.md）',
          typeTransform: null,
          layer: requirementFields[reqField].layer
        });
      } else {
        // 移除字段
        removed.push({
          field: reqField,
          reason: '方案文档定义但Preview未使用',
          layer: requirementFields[reqField].layer
        });
      }
    }
  });

  // 2. 处理新增字段
  Object.keys(previewFields).forEach(previewField => {
    const isMapped = mappings.some(m => m.previewProp === previewField);
    if (!isMapped) {
      added.push({
        field: previewField,
        reason: 'UI需求补充或Figma语义字段',
        type: previewFields[previewField].type
      });
    }
  });

  // 生成报告
  const report = {
    timestamp: new Date().toISOString(),
    componentName,
    sources: {
      requirement: `${componentName}/phase0/requirement-fields.json`,
      preview: `${componentName}/phase2/preview-props-schema.json`
    },
    summary: {
      requirementFields: Object.keys(requirementFields).length,
      previewFields: Object.keys(previewFields).length,
      mappedFields: mappings.length,
      removedFields: removed.length,
      addedFields: added.length
    },
    mappings,
    removed,
    added,
    transformationRules: {
      namingStandards: Object.keys(namingStandards).length,
      typeConversions: Object.keys(typeRules).length
    }
  };

  // 保存到 phase2 目录
  const outputDir = path.join(root, componentName, 'phase2');
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  const outputFile = path.join(outputDir, 'field-mapping.json');
  fs.writeFileSync(outputFile, JSON.stringify(report, null, 2));

  console.log(`\n✅ 字段映射已生成: ${outputFile}`);
  console.log(`\n📊 统计结果:`);
  console.log(`  映射字段: ${mappings.length}`);
  console.log(`  移除字段: ${removed.length}`);
  console.log(`  新增字段: ${added.length}`);

  if (removed.length > 0) {
    console.log(`\n⚠️  移除字段 (${removed.length}):`);
    removed.forEach(r => console.log(`  - ${r.field} (${r.reason})`));
  }

  if (added.length > 0) {
    console.log(`\n➕ 新增字段 (${added.length}):`);
    added.forEach(a => console.log(`  - ${a.field} (${a.reason})`));
  }

  return report;
}

// CLI 执行
function main() {
  const componentName = process.argv[2];

  if (!componentName) {
    console.error('❌ 缺少组件名称');
    console.error('用法: node scripts/phase2/generate-field-mapping.js ComponentName');
    process.exit(1);
  }

  try {
    generateFieldMapping(componentName);
  } catch (error) {
    console.error(`\n❌ 生成字段映射失败: ${error.message}`);
    process.exit(1);
  }
}

main();
